<template>
  <div class="user-score-component">
    <!-- 积分卡片 -->
    <div class="card">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">我的积分</h5>
        <button class="btn btn-sm btn-outline-success" @click="refreshUserScore">
          <span v-if="isLoadingScore" class="spinner-border spinner-border-sm me-1"></span>
          刷新积分
        </button>
      </div>
      <div class="card-body">
        <div v-if="loading" class="text-center py-3">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <p class="mt-2">正在获取积分信息...</p>
        </div>
        <div v-else>
          <div class="text-center mb-4">
            <div class="score-display">
              <span class="score-value">{{ score }}</span>
              <span class="score-label">积分</span>
            </div>
          </div>
          
          <div class="sign-in-section p-4 border rounded text-center">
            <h6 class="mb-2">每日签到</h6>
            <p class="text-muted small mb-3">签到即可获得5积分</p>
            <button 
              class="btn sign-in-btn" 
              :class="buttonClass"
              @click="handleSignIn"
              :disabled="isSigningIn || hasSigned"
            >
              <span v-if="isSigningIn" class="spinner-border spinner-border-sm me-1"></span>
              <i v-else-if="hasSigned" class="bi bi-check-circle-fill me-1"></i>
              {{ signInButtonText }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { authService } from '../api';
import { useUserStore } from '../store/userStore';

export default {
  name: 'UserScore',
  data() {
    const userStore = useUserStore();
    return {
      score: userStore.userPoints,
      loading: true,
      isLoadingScore: false,
      isSigningIn: false,
      hasSigned: false,
      signInButtonText: '立即签到',
      error: null,
      scoreRecords: [
        { title: '完成命理测试', amount: 10, type: 'add', date: '2023-06-15 14:30' },
        { title: '性格分析服务', amount: 30, type: 'sub', date: '2023-06-12 10:45' },
        { title: '每日签到', amount: 5, type: 'add', date: '2023-06-10 08:15' }
      ]
    };
  },
  computed: {
    // 根据签到状态计算按钮样式
    buttonClass() {
      if (this.isSigningIn) return 'btn-secondary';
      if (this.hasSigned) return 'btn-success';
      return 'btn-primary';
    }
  },
  mounted() {
    console.log('UserScore 组件挂载中...');
    // 获取最新积分
    this.fetchUserScore()
      .then(() => console.log('积分获取完成'))
      .catch(err => console.error('积分获取失败:', err));
    
    // 检查今日是否已签到
    this.checkSignInStatus()
      .then(() => console.log('签到状态检查完成, 状态:', this.hasSigned ? '已签到' : '未签到'))
      .catch(err => console.error('签到状态检查失败:', err));
  },
  methods: {
    async fetchUserScore() {
      this.loading = true;
      this.error = null;
      
      try {
        // 使用userStore统一获取积分
        const userStore = useUserStore();
        const result = await userStore.getUserScore();
        
        if (result.success) {
          this.score = result.score;
        } else {
          this.error = result.error || '获取积分失败';
          console.error('获取积分失败:', result.error);
        }
      } catch (error) {
        this.error = '获取积分失败，请稍后重试';
        console.error('获取积分出错:', error);
      } finally {
        this.loading = false;
      }
    },
    async refreshUserScore() {
      if (this.isLoadingScore) return;
      
      this.isLoadingScore = true;
      this.error = null;
      
      try {
        // 使用userStore统一获取积分
        const userStore = useUserStore();
        const result = await userStore.getUserScore();
        
        if (result.success) {
          this.score = result.score;
        } else {
          this.error = result.error || '刷新积分失败';
          console.error('刷新积分失败:', result.error);
        }
      } catch (error) {
        this.error = '刷新积分失败，请稍后重试';
        console.error('刷新积分出错:', error);
      } finally {
        this.isLoadingScore = false;
      }
    },
    async handleSignIn() {
      if (this.isSigningIn || this.hasSigned) return;
      
      this.isSigningIn = true;
      console.log('开始签到流程...');
      
      try {
        const userStore = useUserStore();
        console.log('调用签到接口...');
        const result = await userStore.signIn();
        console.log('签到接口返回结果:', result);
        
        if (result.success) {
          // 签到成功
          console.log('签到成功，更新UI状态');
          this.score = userStore.userPoints;
          this.hasSigned = true;
          this.signInButtonText = '今日已签到';
          
          // 记录今天的签到
          const todayDate = new Date().toISOString().split('T')[0];
          localStorage.setItem('lastSignInDate', todayDate);
          console.log('已更新本地存储签到记录:', todayDate);
          
          // 显示成功提示
          this.showAlert('success', `签到成功！获得${result.addedScore}积分`);
        } else if (result.alreadySigned) {
          // 今日已签到
          console.log('今日已签到，更新UI状态');
          this.hasSigned = true;
          this.signInButtonText = '今日已签到';
          
          // 更新签到记录
          const todayDate = new Date().toISOString().split('T')[0];
          localStorage.setItem('lastSignInDate', todayDate);
          console.log('已更新本地存储签到记录:', todayDate);
          
          this.showAlert('info', result.message || '今日已签到');
        } else {
          // 其他错误
          console.error('签到失败:', result.message);
          this.showAlert('danger', result.message || '签到失败，请稍后重试');
        }
      } catch (error) {
        console.error('签到失败:', error);
        this.showAlert('danger', '签到失败，请稍后重试');
      } finally {
        this.isSigningIn = false;
        console.log('签到流程结束');
      }
    },
    async checkSignInStatus() {
      try {
        console.log('开始检查签到状态...');
        
        // 直接调用API服务检查签到状态，不从本地存储读取
        console.log('调用签到状态检查API...');
        const result = await authService.checkSignInStatus();
        console.log('API返回签到状态结果:', result);
        
        if (!result.success) {
          console.error('API返回失败:', result.message);
          return;
        }
        
        // 确认签到状态
        const isSigned = !!result.isSigned; // 确保是布尔值
        console.log('解析得到的签到状态:', isSigned);
        
        // 更新UI状态
        this.hasSigned = isSigned;
        this.signInButtonText = isSigned ? '今日已签到' : '立即签到';
        
        if (isSigned) {
          // 记录今天已签到到本地存储
          const todayDate = new Date().toISOString().split('T')[0];
          localStorage.setItem('lastSignInDate', todayDate);
          console.log('已更新本地存储签到记录');
        }
        
        console.log('签到状态检查完成, 按钮文本:', this.signInButtonText);
      } catch (error) {
        console.error('检查签到状态错误:', error);
      }
    },
    showAlert(type, message) {
      // 使用事件总线或其他方式向父组件发送消息
      this.$emit('showAlert', { type, message });
      
      // 使用全局 Toast 方法
      if (window.showToast) {
        window.showToast(message, { type });
      } else if (this.$root && this.$root.$toast) {
        // 使用 root 上挂载的 toast
        this.$root.$toast.show(message, { type });
      } else {
        // 简单的方法：使用 console
        console.log(`[${type.toUpperCase()}] ${message}`);
      }
    }
  }
};
</script>

<style scoped>
.user-score-component .card {
  border: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.score-display {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  background-color: #f8f9fa;
  border-radius: 50%;
  width: 120px;
  height: 120px;
  justify-content: center;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
}

.score-value {
  font-size: 2.5rem;
  font-weight: bold;
  color: #198754;
  line-height: 1;
}

.score-label {
  font-size: 0.9rem;
  color: #6c757d;
  margin-top: 0.5rem;
}

.sign-in-section {
  background-color: #f9f9f9;
  margin-bottom: 1rem;
}

.sign-in-btn {
  min-width: 160px;
  padding: 0.5rem 1.5rem;
  border-radius: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  font-size: 0.9rem;
  transition: all 0.3s ease;
}

.sign-in-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
</style> 